<template>
  <div>
    <button @click="add">添加</button>
    &nbsp;&nbsp;
    <button @click="sortt('studentid')">学号排序</button>
    &nbsp;&nbsp;
    <button @click="sortt('age')">年龄排序</button>
    <el-table
        :data="tableData"
        style="width: 60%"
        :row-style="getRowStyle"
        @row-click="onRowClick"
    >
      <el-table-column prop="studentid" label="学号" width="180">
      </el-table-column>
      <el-table-column prop="name" label="姓名" width="180">
      </el-table-column>
      <el-table-column prop="gender" label="性别" width="180">
      </el-table-column>
      <el-table-column prop="age" label="年龄">
      </el-table-column>
    </el-table>
    <br/>
    <button @click="update()">修改{{udname}}</button>
    <br/>
    <br/>
    <div class="block">
      <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage4"
          :page-sizes="[10, 20, 30, 40]"
          :page-size="size"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total">
      </el-pagination>
    </div>

    <el-dialog title="修改" :visible.sync="dialogFormVisible">
      <el-form :model="form">
        <el-form-item label="学号" :label-width="formLabelWidth">
          <el-input v-model="form.studentid" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="姓名" :label-width="formLabelWidth">
          <el-input v-model="form.name" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="学院" :label-width="formLabelWidth">
          <el-select v-model="dept" placeholder="请选择">
            <el-option
                v-for="item in options1"
                :key="item.value"
                :label="item.label"
                :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="专业" :label-width="formLabelWidth">
          <el-select v-model="major" placeholder="请选择">
            <el-option
                v-for="item in options2"
                :key="item.value"
                :label="item.label"
                :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="年龄" :label-width="formLabelWidth">
          <el-input v-model="form.age" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="性别" :label-width="formLabelWidth">
          <el-input v-model="form.gender" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <p style="color: red;font-size: 20px">{{messages}}</p>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="save">确 定</el-button>
      </div>
    </el-dialog>

    <el-dialog title="添加" :visible.sync="dialogFormVisible2">
      <el-form :model="form2">
        <el-form-item label="学号" :label-width="formLabelWidth">
          <el-input v-model="form2.studentid" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="姓名" :label-width="formLabelWidth">
          <el-input v-model="form2.name" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="学院" :label-width="formLabelWidth">
          <el-select v-model="dept2" placeholder="请选择">
            <el-option
                v-for="item in options1"
                :key="item.value"
                :label="item.label"
                :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="专业" :label-width="formLabelWidth">
          <el-select v-model="major2" placeholder="请选择">
            <el-option
                v-for="item in options2"
                :key="item.value"
                :label="item.label"
                :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="年龄" :label-width="formLabelWidth">
          <el-input v-model="form2.age" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="性别" :label-width="formLabelWidth">
          <el-input v-model="form2.gender" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <p style="color: red;font-size: 20px">{{messages}}</p>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible2 = false">取 消</el-button>
        <el-button type="primary" @click="save2">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import axios from "axios";

export default {
  data() {
    return {
      messages:'',
      formLabelWidth: '40px',
      tableData: [],
      currentPage4: 1,
      total: 0,
      size: 10,
      sort: null,
      udname:'',
      selectedRow: null,
      dialogFormVisible: false,
      dialogFormVisible2: false,
      form: {
        studentid: '',
        name: '',
        age: '',
        gender: '',
        dept: '',
        major: ''
      },
      form2: {
        studentid: '',
        name: '',
        age: '',
        gender: '',
        dept: '',
        major: ''
      },
      major:'',
      dept:'',
      major2:'',
      dept2:'',
      options1: [],
      options2: [],
      majors: [],
      depts:[],
      up_down: 1, // 降序
    };
  },
  methods: {
    getRowStyle({ row }) {
      if (row === this.selectedRow) {
        return { background: 'red' }; // 如果是选中的行，则背景为红色
      }
      if (row.studentid === this.selectedRow?.studentid) {
        return { background: 'red' };
      }
      if (row.gender === '男') {
        return { background: '#ADD8E6' }; // Light blue
      } else if (row.gender === '女') {
        return { background: '#FFC0CB' }; // Light pink
      }
      return {};
    },
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`);
      this.size = val;
      this.select();
    },
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`);
      this.currentPage4 = val;
      this.select();
      this.selectedRow = null;
    },
    select(st) {
      axios.get('http://localhost:9000/student', {
        params: {
          PageNum: this.currentPage4,
          PageSize: this.size,
          orderBy: this.sort
        }
      }).then((res) => {
        this.tableData = res.data.content.list;
        this.total = res.data.content.total;
        // 页面一加载 自动选中当前行
        this.selectFirstRow();
      })
    },
    sortt(st) {
      if (this.up_down % 2 == 0) {
        this.up_down++;
        this.sort = st + ' desc';
      } else {
        this.up_down++;
        this.sort = st + ' asc';
      }
      // 排序
      console.log('排序',this.sort);
      this.select();
      this.selectedRow = null;
    },
    onRowClick(row) {
      this.dept = '';
      this.major = '';
      console.log('点击了第', row.studentid, '号学生的信息:', row);

      this.options1.forEach((item)=> {
        if (item.id == row.dept){
          this.dept = item.value;
        }
      })
      this.options2.forEach((item)=> {
        if (item.id == row.major){
          this.major = item.value;
        }
      })

      this.udname = row.name;
      this.selectedRow = row;
    },
    selectFirstRow() {
      if (this.selectedRow != null) {
        console.log(this.selectedRow,777)
        this.tableData.forEach((row)=>{
          if (row.studentid === this.selectedRow.studentid) {
            this.selectedRow = row;
            this.udname = row.name;
            return;
          }
        })
      }
      if (this.tableData.length > 0 && this.selectedRow == null) {
        this.selectedRow = this.tableData[0]; // 第一次选中第一行
        this.udname = this.selectedRow.name;
        this.options1.forEach((item)=> {
          if (item.id == this.selectedRow.dept){
            this.dept = item.value;
          }
        })
        this.options2.forEach((item)=> {
          if (item.id == this.selectedRow.major){
            this.major = item.value;
          }
        })
      }
    },
    // 更新学生
    update(){
      console.log(this.selectedRow);
      this.form = JSON.parse(JSON.stringify(this.selectedRow));
      this.dialogFormVisible = true;
    },
    save() {
      // 校验
      if (this.form.studentid == '') {
        this.messages = '学号不能为空';
        return;
      }
      if (this.form.name == '') {
        this.messages = '姓名不能为空';
        return;
      }
      // 姓名是否超过字符串长度范围（20个字符）
      if (this.form.name.length > 20) {
        this.messages = '姓名不能超过20个字符';
        return;
      }
      if (this.form.age == '') {
        this.messages = '年龄不能为空';
        return;
      }
      // 年龄是否输入了不合法字符
      if (isNaN(this.form.age)) {
        this.messages = '年龄只能输入数字';
        return;
      }
      // 年龄是否输入了超过合理年龄的范围（0～120岁）
      if (this.form.age < 0 || this.form.age > 120) {
        this.messages = '年龄必须在0～120岁之间';
        return;
      }
      if (this.form.gender == '') {
        this.messages = '性别不能为空';
        return;
      }
      if (this.dept == '') {
        this.messages = '请选择部门';
        return;
      }
      if (this.major == '') {
        this.messages = '请选择专业';
        return;
      }

      this.options1.forEach((item)=> {
        if (item.value == this.dept){
          this.form.dept = item.id;
        }
      })
      this.options2.forEach((item)=> {
        if (item.value == this.major){
          this.form.major = item.id;
        }
      })
      axios.post('http://localhost:9000/student/save', this.form).then(() => {
        if (this.sort == 'age') {
          this.selectedRow = null;
          console.log('找age排序修改后的那行数据');
          // ---------------------------
          for (let i = 1; i <= 10; i++) {
            axios.get('http://localhost:9000/student', {
              params: {
                PageNum: i,
                PageSize: this.size,
                orderBy: this.sort
              }
            }).then((res) => {
              const temp = res.data.content.list;
              // 遍历每一页
              for (let j = 0; j < temp.length; j++) {
                // 遍历每一行
                if (temp[j].studentid === this.form.studentid) {
                  // 找到匹配的行
                  console.log("找到匹配的行", j,"第几页：", i);
                  axios.get('http://localhost:9000/student', {
                    params: {
                      PageNum: i,
                      PageSize: this.size,
                      orderBy: this.sort
                    }
                  }).then((res) => {
                    this.tableData = res.data.content.list;
                    this.total = res.data.content.total;
                    this.currentPage4 = i;
                  });
                  console.log(temp[j]);
                  this.selectedRow = temp[j];
                  this.tableData.forEach((row)=>{
                    if (row.studentid === this.selectedRow.studentid) {

                    }
                  })
                  this.udname = temp[j].name;
                  return;
                }
              }
            })
          }
          // -----------------------------
          this.dialogFormVisible = false;
        } else {
          this.select();
          this.selectFirstRow();
          this.dialogFormVisible = false;
        }
      })
    },
    getDept() {
      axios.get('http://localhost:9000/dept').then((res) => {
        this.depts = res.data;
        this.options1 = res.data.map(item => ({
          value: item.dept,
          id: item.id
        }));
      })
   },
    getMajors() {
      axios.get('http://localhost:9000/deptMajor').then((res) => {
        this.majors = res.data;
        this.options2 = res.data.map(item => ({
          value: item.major,
          id: item.id
        }));
      })
   },
    add() {
      this.messages= '';
      this.form2 = {
            studentid: '',
            name: '',
            age: '',
            gender: '',
            dept: '',
            major: ''
      }
      this.dept2 = '';
      this.major2 = '';
      // 获取id
      axios.get('http://localhost:9000/student/select-max-id').then((res) => {
        this.form2.studentid = res.data;
      })
      this.dialogFormVisible2 = true;
    },
    save2() {
      // 校验
      if (this.form2.studentid == '') {
        this.messages = '学号不能为空';
        return;
      }
      if (this.form2.name == '') {
        this.messages = '姓名不能为空';
        return;
      }
      // 姓名是否超过字符串长度范围（20个字符）
      if (this.form2.name.length > 20) {
        this.messages = '姓名不能超过20个字符';
        return;
      }
      if (this.form2.age == '') {
        this.messages = '年龄不能为空';
        return;
      }
      // 年龄是否输入了不合法字符
      if (isNaN(this.form2.age)) {
        this.messages = '年龄只能输入数字';
        return;
      }
      // 年龄是否输入了超过合理年龄的范围（0～120岁）
      if (this.form2.age < 0 || this.form2.age > 120) {
        this.messages = '年龄必须在0～120岁之间';
        return;
      }
      if (this.form2.gender == '') {
        this.messages = '性别不能为空';
        return;
      }
      if (this.dept2 == '') {
        this.messages = '请选择部门';
        return;
      }
      if (this.major2 == '') {
        this.messages = '请选择专业';
        return;
      }

      this.options1.forEach((item)=> {
        if (item.value == this.dept2){
          this.form2.dept = item.id;
        }
      })
      this.options2.forEach((item)=> {
        if (item.value == this.major2){
          this.form2.major = item.id;
        }
      })
      axios.post('http://localhost:9000/student/save2', this.form2).then((res) => {
        if (res.data.success) {
          //this.select();
          this.dialogFormVisible2 = false;

          // ---------------------------
          for (let i = 1; i <= 10; i++) {
            axios.get('http://localhost:9000/student', {
              params: {
                PageNum: i,
                PageSize: this.size,
              }
            }).then((res) => {
              const temp = res.data.content.list;
              // 遍历每一页
              for (let j = 0; j < temp.length; j++) {
                // 遍历每一行
                if (temp[j].studentid === this.form2.studentid) {
                  // 找到匹配的行
                  console.log("找到匹配的行", j,"第几页：", i);
                  axios.get('http://localhost:9000/student', {
                    params: {
                      PageNum: i,
                      PageSize: this.size,
                    }
                  }).then((res) => {
                    this.tableData = res.data.content.list;
                    this.total = res.data.content.total;
                    this.currentPage4 = i;
                  });
                  console.log(temp[j]);
                  this.selectedRow = temp[j];
                  this.tableData.forEach((row)=>{
                    if (row.studentid === this.selectedRow.studentid) {

                    }
                  })
                  this.udname = temp[j].name;
                  return;
                }
              }
            })
          }
          // -----------------------------
        } else {
          this.messages = res.data.message;
        }
      });
    }
  },
  mounted() {
    this.getDept();
    this.getMajors();
    this.select();
  }
};
</script>